package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.pojo.dto.UserAuthorizationSaveDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.service.UserAuthorizationService;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author WuHB
 * @date 2022/08/30 16:16
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/userAuthorization")
public class UserAuthorizationController {

    @Resource
    private UserAuthorizationService userAuthorizationService;

    /**
     * 用户授权信息保存
     *
     * @param saveDto 保存类
     * @param br      br
     * @return 影响行数
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String save(@RequestBody @Valid UserAuthorizationSaveDTO saveDto, BindingResult br) throws Exception {
        XbbResponse<Integer> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                Integer save = userAuthorizationService.save(saveDto);
                response = new XbbResponse<>(save);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }

        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

}
